import React, {Component} from 'react';
import {
    Form,
    Icon,
    Input,
    Button,
    Row,
    Col,
    Select,
    message,
    Card,
    Popconfirm,
    List,
    Breadcrumb
} from 'antd';
import './AddStateFLow.css';
import Keys from "../../config/Keys";
import CRUDStateFlowService from "../../service/CRUDStateFlowService";

class AddStateFlow extends Component {


    data = {
        name: '',
        stateFlows: [{
            state: '',
            stateName: '',
            operators: [{
                operatorCode: '',
                operatorName: '',
                notifyType: '',
                notifyUrl: '',
                nextState: '',
            }]
        }]
    };

    /** 选中的状态 */
    selectState = {};

    /** 历史操作码 */
    operatorOption = [];

    /** 刷新 */
    refresh() {
        this.setState({
            ...this.state
        });
    }


    /**
     * 在渲染前调用
     * */
    componentWillMount() {
        let context = this.props.context;
        if (context.params && context.params.operator === 'UPDATE') {
            this.data = context.params.stateFlowConfig;
        }
    }


    /**
     * 绑定状态模型输入框
     * @param e
     * @param model
     */
    bindStateInput = (e, model) => {

        // 更新状态数据
        for (let i = 0; i < this.data.stateFlows.length; i++) {
            let item = this.data.stateFlows[i];
            if (item.id === model.id) {

                this.data.stateFlows[i] = {
                    ...item,
                    [e.id]: e.value
                };
                break;
            }
        }
    };


    /**
     * 绑定操作模型输入框
     * @param e
     * @param model
     */
    bindOperatorInput = (e, model) => {

        // 更新操作数据
        for (let i = 0; i < this.data.stateFlows.length; i++) {
            let item = this.data.stateFlows[i];

            if (item === undefined || item.operators === undefined || item.operators.length === 0) {
                continue;
            }

            for (let b = 0; b < item.operators.length; b++) {
                let operator = item.operators[b];
                if (operator.id === model.id) {
                    this.data.stateFlows[i].operators[b] = {
                        ...operator,
                        [e.id]: e.value
                    };
                    break;
                }
            }
        }

    };

    /**
     * 给列表内每一项创建ID
     * @param stateFlows
     */
    createId = (stateFlows) => {

        if (stateFlows === undefined || stateFlows.length === 0) return;

        let id = 1;
        for (let item of stateFlows) {
            item.id = id;
            id++;

            if (item.operators !== undefined && item.operators.length > 0) {

                for (let o of item.operators) {
                    o.id = id;
                    id++;
                }
            }
        }
    };


    /**
     * 添加已有操作信息 <Select.Option>
     * @param operatorOption
     * @param operators
     */
    setOperatorOption = (operators) => {

        let _operatorOption = [];
        let inOperators = [];
        let index = 10001;
        for (let operator of operators) {
            if (operator.operatorCode !== undefined && operator.operatorCode.trim().length > 0) {
                let b = this.checkOperatorOption(inOperators, operator);
                if (b === false) {
                    _operatorOption.push(
                        <Select.Option
                            value={JSON.stringify(operator)}
                            key={index}>
                            {operator.operatorCode + '(' + operator.operatorName + ')'}
                        </Select.Option>
                    );
                    inOperators.push(operator);
                    index++;
                }
            }
        }

        if (_operatorOption.length > this.operatorOption.length) {
            this.operatorOption = _operatorOption;
        }

    };


    /**
     * 检查已有操作信息是否已经添加过，根据operatorCode
     * @param inOperators
     * @param operator
     * @returns {boolean}
     */
    checkOperatorOption = (inOperators, operator) => {
        let b = false;
        for (let i = 0; i < inOperators.length; i++) {
            let item = inOperators[i];
            if (item.operatorCode === operator.operatorCode) {
                b = true;
                break;
            }
        }

        return b;
    };


    /** 提交数据 */
    submitDataClick = () => {
        if (this.data.name === undefined || this.data.name.trim().length === 0) {
            message.warn("请填写状态流转配置名称");
            return;
        }

        let context = this.props.context;
        let requestParam = {
            accessKey: context.userInfo.accessKey,
            stateFlowConfig: this.data
        };

        if (context.params && context.params.operator === 'UPDATE') {

            CRUDStateFlowService.modify(requestParam,
                () => {
                    message.success("修改状态流转配置成功");
                    context.openPage(Keys.PAGE_CODES.HOME, null);
                });

        } else {

            CRUDStateFlowService.create(requestParam,
                () => {
                    message.success("添加状态流转配置成功");
                    context.openPage(Keys.PAGE_CODES.HOME, null);
                });
        }

    };

    render() {

        this.createId(this.data.stateFlows);


        let stateOption = [];
        if (this.data.stateFlows !== undefined && this.data.stateFlows.length > 0) {
            for (let stateItem of this.data.stateFlows) {

                //设置状态下拉框内容
                if (stateItem.state !== undefined && stateItem.state.trim().length > 0) {
                    stateOption.push(
                        <Select.Option
                            value={stateItem.state}
                            key={stateItem.id}>
                            {stateItem.state + '（' + stateItem.stateName + '）'}
                        </Select.Option>
                    );
                }

                //设置一键选择下拉框内容
                if (stateItem.operators !== undefined && stateItem.operators.length > 0) {
                    this.setOperatorOption(stateItem.operators);
                }
            }
        }

        //拼接状态名称
        let selectStateName =
            this.selectState.stateName === undefined || this.selectState.stateName.trim().length === 0
                ? ''
                : '（' + this.selectState.state + ' ' + this.selectState.stateName + '）';


        return (

            <div>

                <div>

                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <a onClick={() => {
                                let context = this.props.context;
                                context.openPage(Keys.PAGE_CODES.HOME, null);
                            }}>
                                首页
                            </a>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            状态流转配置页
                        </Breadcrumb.Item>
                    </Breadcrumb>

                </div>

                <div style={{height: '20px'}}/>

                <Card title={'自定义名称'}>
                    <Input placeholder={'自定义状态流转配置名称'}
                           defaultValue={this.data.name}
                           onChange={(e) => {
                               this.data.name = e.target.value;
                           }}/>
                </Card>

                <div style={{height: '50px'}}/>

                <Card
                    title={'状态流转配置'}
                    bodyStyle={{padding: '30px', background: '#f5f5f5'}}>

                    {/*状态列表*/}
                    <Col span={11}>
                        <Card title={'状态列表'} type="inner">

                            <List
                                itemLayout={'horizontal'}
                                dataSource={this.data.stateFlows}
                                renderItem={item => (
                                    <List.Item
                                        actions={[
                                            <a onClick={() => {
                                                this.selectState = item;
                                                this.refresh();
                                            }}
                                            >选中</a>,

                                            <Popconfirm
                                                title="确认要进行该操作吗?"
                                                onConfirm={() => {
                                                    let newStateFlows = [];
                                                    for (let stateItem of this.data.stateFlows) {
                                                        if (stateItem.state !== item.state) {
                                                            newStateFlows.push(stateItem);
                                                        }
                                                    }

                                                    this.data.stateFlows = newStateFlows;
                                                    this.refresh();
                                                }}
                                                okText="是"
                                                cancelText="否"
                                            >
                                                <a>删除</a>
                                            </Popconfirm>

                                        ]}>
                                        <Col>
                                            状态码 ：
                                            <Input
                                                defaultValue={item.state}
                                                key={item.state}
                                                id={'state'}
                                                onChange={(e) => {
                                                    this.bindStateInput(e.target, item);
                                                }}
                                                className={'asf-state-input'}/>
                                        </Col>
                                        <Col>
                                            状态名称 ：
                                            <Input
                                                defaultValue={item.stateName}
                                                key={item.state + item.stateName}
                                                id={'stateName'}
                                                onChange={(e) => {
                                                    this.bindStateInput(e.target, item);
                                                }}
                                                className={'asf-state-input'}/>
                                        </Col>
                                    </List.Item>
                                )}/>


                            <Button
                                type="dashed"
                                style={{width: '100%', marginTop: '20px'}}
                                icon="plus-circle"
                                onClick={() => {
                                    this.data.stateFlows.push({});
                                    this.refresh();
                                }}>
                                Add
                            </Button>
                        </Card>

                    </Col>

                    <Col span={2}/>

                    {/*状态下操作列表*/}
                    <Col span={11}>
                        <Card title={selectStateName + '状态下操作列表'} type="inner">

                            <List
                                itemLayout={'horizontal'}
                                dataSource={this.selectState.operators}
                                split={false}
                                renderItem={item => (
                                    <List.Item
                                        actions={[
                                            <Popconfirm
                                                title="确认要进行该操作吗?"
                                                onConfirm={() => {

                                                    let newOperators = [];
                                                    for (let o of this.selectState.operators) {
                                                        if (o.id !== item.id) {
                                                            newOperators.push(o);
                                                        }
                                                    }

                                                    this.selectState.operators = newOperators;

                                                    for (let i = 0;i < this.data.stateFlows.length;i++){
                                                        let s = this.data.stateFlows[i];
                                                        if (s.id === this.selectState.id){
                                                            this.data.stateFlows[i].operators = newOperators
                                                        }
                                                    }

                                                    this.refresh();
                                                }}
                                                okText="是"
                                                cancelText="否"
                                            >
                                                <a>删除</a>
                                            </Popconfirm>

                                        ]}>
                                        <Card>
                                            <div>
                                                <Row>
                                                    一键选择 ：
                                                    <Select
                                                        key={item.id + 'allSelect'}
                                                        id={'allSelect'}
                                                        onChange={(e) => {
                                                            let operator = JSON.parse(e);
                                                            item.operatorCode = operator.operatorCode;
                                                            item.operatorName = operator.operatorName;
                                                            item.notifyType = operator.notifyType;
                                                            item.notifyUrl = operator.notifyUrl;
                                                            item.nextState = operator.nextState;
                                                            this.refresh();
                                                        }}
                                                        className={'asf-operator-input'}>
                                                        {this.operatorOption}
                                                    </Select>
                                                </Row>
                                                <Row>
                                                    操作编码 ：
                                                    <Input
                                                        defaultValue={item.operatorCode}
                                                        key={item.id + item.operatorCode}
                                                        id={'operatorCode'}
                                                        onChange={(e) => {
                                                            this.bindOperatorInput(e.target, item);
                                                        }}
                                                        className={'asf-operator-input'}/>

                                                </Row>
                                                <Row>
                                                    操作名称 ：
                                                    <Input
                                                        defaultValue={item.operatorName}
                                                        key={item.id + item.operatorName}
                                                        id={'operatorName'}
                                                        onChange={(e) => {
                                                            this.bindOperatorInput(e.target, item);
                                                        }}
                                                        className={'asf-operator-input'}/>
                                                </Row>
                                                <Row>
                                                    通知方式 ：
                                                    <Select
                                                        defaultValue={item.notifyType}
                                                        key={item.id + item.notifyType}
                                                        onChange={(e) => {
                                                            this.bindOperatorInput({id: 'notifyType', value: e}, item);
                                                        }}
                                                        className={'asf-operator-input'}>

                                                        <Select.Option value='HTTP'>HTTP</Select.Option>
                                                        <Select.Option value='RPC' disabled>RPC(暂不支持)</Select.Option>
                                                        <Select.Option value='NO_NOTIFY'>不通知</Select.Option>
                                                    </Select>
                                                </Row>
                                                <Row>
                                                    通知URL ：
                                                    <Input
                                                        defaultValue={item.notifyUrl}
                                                        key={item.id + item.notifyUrl}
                                                        id={'notifyUrl'}
                                                        onChange={(e) => {
                                                            this.bindOperatorInput(e.target, item);
                                                        }}
                                                        className={'asf-operator-input'}/>
                                                </Row>
                                                <Row>
                                                    下一状态 ：
                                                    <Select
                                                        defaultValue={item.nextState}
                                                        key={item.id + item.nextState}
                                                        id={'nextState'}
                                                        onChange={(e) => {
                                                            this.bindOperatorInput({id: 'nextState', value: e}, item);
                                                        }}
                                                        className={'asf-operator-input'}
                                                        onFocus={() => {
                                                            this.refresh();
                                                        }}>
                                                        {stateOption}
                                                    </Select>
                                                </Row>
                                            </div>
                                        </Card>
                                    </List.Item>
                                )}
                            />

                            <Button
                                type="dashed"
                                style={{width: '100%', marginTop: '20px'}}
                                icon="plus-circle"
                                onClick={() => {

                                    if (this.selectState.state === undefined) {
                                        message.warn('请先选中一个状态');
                                        return;
                                    }

                                    if (this.selectState.operators === undefined) {
                                        this.selectState.operators = [];
                                    }
                                    this.selectState.operators.push({});
                                    this.refresh();
                                }}>
                                Add
                            </Button>
                        </Card>
                    </Col>

                </Card>

                <div style={{textAlign: 'center', padding: '30px'}}>
                    <Button type={'primary'} style={{width: '180px'}}
                            onClick={this.submitDataClick}>
                        提交数据
                    </Button>
                </div>
            </div>
        );
    }
}

const AddStateFlowForm = Form.create({name: 'add_state_flow'})(AddStateFlow);
export default AddStateFlowForm;
